<?php

class Application_Model_UserType
{
    /**
     * @param bool $orderByLft
     * @return UserTypePOJO[]
     */
    public static function getUserTypes($orderByLft = null)
    {
        $dbAdapter = JDbAdapter::factory();

        $dbSelect = $dbAdapter->select()->from('USER_TYPES');
        if (isset($orderByLft)) {
            if ($orderByLft) {
                $dbSelect->order('Lft ASC');
            } else {
                $dbSelect->order('Lft DESC');
            }
        }
        $assoc = $dbAdapter->fetchAll($dbSelect);
        $userTypePOJOs = array();
        foreach ($assoc as $row) {
            $userTypePOJO = new UserTypePOJO($row);
            array_push($userTypePOJOs, $userTypePOJO);
        }

        return $userTypePOJOs;
    }

    /**
     * @param int $id
     * @return UserTypePOJO
     */
    public static function getUserType($id)
    {
        $dbAdapter = JDbAdapter::factory();

        $row = $dbAdapter->fetchRow(
            $dbAdapter->select()->from('USER_TYPES')->where("ID = $id")
        );

        if ($row == null) {
            return null;
        }

        return new UserTypePOJO($row);
    }

    /**
     * @param int $id
     * @return int[]
     */
    public static function getUserTypeGroup($id)
    {
        $dbAdapter = JDbAdapter::factory();

        $userTypePOJO = self::getUserType($id);
        $ids = $dbAdapter->fetchCol(
            $dbAdapter->select()
                ->from('USER_TYPES', 'ID')
                ->where('Lft >= ?', $userTypePOJO->Lft)
                ->where('Rgt <= ?', $userTypePOJO->Rgt)
        );

        return $ids;
    }
}

class UserTypePOJO extends POJO
{
    /** @var int */
    public $ID;

    /** @var int */
    public $Lft;

    /** @var int */
    public $Rgt;

    /** @var int */
    public $Level;

    /** @var string */
    public $Name;

    /**
     * @return void
     */
    public function convert()
    {
        $this->ID = (int)$this->ID;
        $this->Lft = (int)$this->Lft;
        $this->Rgt = (int)$this->Rgt;
        $this->Level = (int)$this->Level;
        $this->Name = (string)$this->Name;
    }
}
